/*
 * @Date: 2019-11-18 16:38:52
 * @LastEditTime : 2020-01-11 14:43:33
 * @开    发: lancer
 * @版    本: 1.00
 * @页面描述: 公共方法定义（不参与webpack打包编译
 */

const tool = (function tool() {

/*
1.取整

// 丢弃小数部分,保留整数部分
parseInt(5/2)　　// 2

2.向上取整

// 向上取整,有小数就整数部分加1
Math.ceil(5/2)　　// 3

3.向下取整

// 向下取整,丢弃小数部分
Math.floor(5/2)　　// 2

4四舍五入

// 四舍五入
Math.round(5/2)　　// 3

取余
// 取余
6%4　　// 2

获取该元素所有坐标属性
element.daohang.getBoundingClientRect()

function函数内默认的两个参数 arguments、this
*/

    /**
     * 解决两个数相加精度丢失问题
     */
    function floatAdd(a, b) {
        var c, d, e;
        if(undefined==a||null==a||""==a||isNaN(a)){a=0;}
        if(undefined==b||null==b||""==b||isNaN(b)){b=0;}
        try {
            c = a.toString().split(".")[1].length;
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;
        } catch (f) {
            d = 0;
        }
        e = Math.pow(10, Math.max(c, d));
        return  (floatMul(a, e) + floatMul(b, e)) / e;
    }
    /**
     * 解决两个数相减精度丢失问题
     */
    function floatSub(a, b) {
        var c, d, e;
        if(undefined==a||null==a||""==a||isNaN(a)){a=0;}
        if(undefined==b||null==b||""==b||isNaN(b)){b=0;}
        try {
            c = a.toString().split(".")[1].length;
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;
        } catch (f) {
            d = 0;
        }
        e = Math.pow(10, Math.max(c, d));
        return (floatMul(a, e) - floatMul(b, e)) / e;
    }
    /**
     * 解决两个数相乘精度丢失问题
     */
    function floatMul(a, b) {
        var c = 0,
            d = a.toString(),
            e = b.toString();
        try {
            c += d.split(".")[1].length;
        } catch (f) {}
        try {
            c += e.split(".")[1].length;
        } catch (f) {}
        return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    }
    /**
     * 解决两个数相除精度丢失问题
     */
    function floatDiv(a, b) {
        var c, d, e = 0,
            f = 0;
        try {
            e = a.toString().split(".")[1].length;
        } catch (g) {}
        try {
            f = b.toString().split(".")[1].length;
        } catch (g) {}
        return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), floatMul(c / d, Math.pow(10, f - e));
    }
    //四舍五入保留2位小数（不够位数，则用0替补）
    function floatNumberTwo(num) {
        var result = parseFloat(num);
        if (isNaN(result)) {
        // alert('传递参数错误，请检查！../tool/floatNumberTwo');
        return false;
        }
        result = Math.round(num * 100) / 100;
        var s_x = result.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
        }
        while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
        }
        return s_x;
    }

    //设置cookie
    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + exdays);
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
        return true;
    };
    //获取cookie
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(";");
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == " ") c = c.substring(1);
            if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
        }
        return "";
    };
    //移除cookie
    function delCookie(name) {
        this.setCookie(name, "", -1)
    };
    //设置Session
    function setSession(name, value) {
        window.sessionStorage.setItem(name, value)
    };
    //获取Session
    function getSession(name, value) {
        if(window.sessionStorage.getItem(name)){
            return window.sessionStorage.getItem(name)
        } else {
            return false
        }
    };
    //移除Session
    function delSession(name) {
        window.sessionStorage.removeItem(name)
    };
    //判断是否有滚动条：vertical纵轴，horizontal横轴
    /*
        element.scrollTop 代表目前滾動條和最上方距離多長
        element.scrollHeight 代表整個滾動條多長
        element.scrollHeight - element.scrollTop 就是滾動條與底部距離
    */
    function hasScrolled(element,direction){
        if(direction==='vertical'){
            return element.scrollHeight>element.clientHeight;
        }else if(direction==='horizontal'){
            return element.scrollWidth>element.clientWidth;
        }
    };
    //div标签绝对坐标位置获取脚本
    function getXY(element)
    {
        var Left=0,Top=0;
        do{Left+=element.offsetLeft,Top+=element.offsetTop;}
        while(element=element.offsetParent);
    };
    //日期算出差几天
    function getTimes(data){
        var s1 = data
        var s1 = new Date(s1.replace(/-/g, "/"))
        var s2 = new Date()
        var days = s1.getTime() - s2.getTime()
        var time = parseInt(days / (1000 * 60 * 60 * 24));
        return time
    };
    function timeConversion(tims, type) {//传时间戳 和 美东  返回 数组[年，月，日，时，分，秒，星期]
        let year, month, strDate, sDate, fDate, mDate, day
        if(String(tims).length==16){
            var tim = new Date(Math.round(tims/1000));//时间戳为16位需*1000，时间戳为13位的话不需乘1000
        }else if(String(tims).length==10) {
            var tim = new Date(tims * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        }else{
            var tim = new Date(tims);//时间戳为13位需*1000，时间戳为13位的话不需乘1000
        }
        year = tim.getFullYear();//年
        month = ('0' + (tim.getMonth() + 1)).slice(-2);//月
        strDate = ('0' + tim.getDate()).slice(-2);//日
        sDate = ('0' + tim.getHours()).slice(-2);//时
        fDate = ('0' + tim.getMinutes()).slice(-2);//分
        mDate = ('0' + tim.getSeconds()).slice(-2);//秒
        day = tim.getDay()//星期几
        switch (day) {  //星期几
            case 0:
                day = "日";
                break;
            case 1:
                day = "一";
                break;
            case 2:
                day = "二";
                break;
            case 3:
                day = "三";
                break;
            case 4:
                day = "四";
                break;
            case 5:
                day = "五";
                break;
            case 6:
                day = "六";
                break;
        }

        if(type===1){
            return [year+'/'+month+'/'+strDate+' '+sDate+':'+fDate+':'+mDate]
        }
        return [year, month, strDate, sDate, fDate, mDate, day]
    };
    function getUnixTime(dateStr){ // 时间格式转换成时间戳 //getUnixTime('2019-06-17 23:11:54');
        var newstr = dateStr.replace(/-/g,'/'); 
        var date =  new Date(newstr); 
        var time_str = date.getTime().toString();
        return time_str.substr(0, 10);
    };
    function getRandomNumberByRange(start, end) {
        return Math.floor(Math.random() * (end - start) + start)
    };
    //抛出接口方法
    return {
        setCookie: setCookie,
        getCookie: getCookie,
        delCookie: delCookie,
        setSession: setSession,
        getSession: getSession,
        delSession: delSession,
        hasScrolled: hasScrolled,
        getTimes: getTimes,
        timeConversion: timeConversion,
        floatAdd: floatAdd,
        floatSub: floatSub,
        floatMul: floatMul,
        floatDiv: floatDiv,
        floatNumberTwo: floatNumberTwo,
        getUnixTime: getUnixTime,
        getRandomNumberByRange: getRandomNumberByRange,
    }
}())

export { tool }